package com.example.yifei.ui.page.login

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.yifei.R
import com.example.yifei.data.http.HttpResult
import com.example.yifei.data.http.HttpService
import com.example.yifei.utils.AppUserUtil
import com.example.yifei.utils.showToast
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @Author: zhudaihao
 * @Date: 2022/5/6
 * @Describe: 登录vm
 */

@HiltViewModel
class LoginViewModel @Inject constructor(
    private var service: HttpService
) : ViewModel() {
    //定义状态对象
    var viewStates by mutableStateOf(LoginViewState())
        private set
    private val _viewEvents = Channel<LoginViewEvent>(Channel.BUFFERED)    //创建订阅者
    val viewEvents = _viewEvents.receiveAsFlow()

    //处理状态逻辑
    fun dispatch(loginViewAction: LoginViewAction) {
        when (loginViewAction) {
            is LoginViewAction.Login -> login()
            is LoginViewAction.CleanAccount -> cleanAccount()
            is LoginViewAction.CleanPassword -> cleanPassword()
            is LoginViewAction.UpdateAccount -> updateAccount(loginViewAction.account)
            is LoginViewAction.UpdatePassword -> updatePassword(loginViewAction.password)
            is LoginViewAction.PasswordState -> passwordStateUpdate()
            is LoginViewAction.UpdateAgreement -> updateAgreement()
        }
    }


    //清除密码
    private fun cleanPassword() {
        viewStates = viewStates.copy(password = "", cleanPasswordSize = 0.dp)

    }


    //更新勾选协议状态
    private fun updateAgreement() {
        viewStates = viewStates.copy(isAgreement = !viewStates.isAgreement)
    }

    //密码是否隐藏
    private fun passwordStateUpdate() {
        viewStates = if (viewStates.passwordRes == R.mipmap.icon_eye_active) {
            viewStates.copy(
                passwordRes = R.mipmap.icon_eye_default,
                visualTransformation = VisualTransformation.None
            )
        } else {
            viewStates.copy(
                passwordRes = R.mipmap.icon_eye_active,
                visualTransformation = PasswordVisualTransformation()
            )
        }
    }

    //更新输入密码数据
    private fun updatePassword(password: String) {
        viewStates = if (password.isEmpty()) {
            viewStates.copy(cleanPasswordSize = 0.dp, password = password)
        } else {
            viewStates.copy(cleanPasswordSize = 20.dp, password = password)
        }
    }

    //更新输入账号数据
    private fun updateAccount(account: String) {
        viewStates = if (account.isEmpty()) {
            viewStates.copy(cleanAccountSize = 0.dp, account = account)
        } else {
            viewStates.copy(cleanAccountSize = 20.dp, account = account)
        }
    }

    //点击账号清除按钮
    private fun cleanAccount() {
        viewStates = viewStates.copy(account = "")
        viewStates = viewStates.copy(cleanAccountSize = 0.dp)
    }


    //点击登录按钮
    private fun login() {
        if (viewStates.account.isEmpty()) {
            showToast("请输入账号")
            return
        }

        if (viewStates.password.isEmpty()) {
            showToast("请输入密码")
            return
        }

        if (!viewStates.isAgreement) {
            showToast("请勾选条款")
            return
        }

        viewModelScope.launch {
            flow {
                emit(service.login(viewStates.account.trim(), viewStates.password.trim()))
            }.map {
                //解析数据
                if (it.errorCode == 0) {
                    if (it.data != null) {
                        HttpResult.Success(it.data!!)
                    } else {
                        throw Exception("the result of remote's request is null")
                    }
                } else {
                    throw Exception(it.errorMsg)
                }
            }.onEach {
                //成功
                AppUserUtil.onLogin(it.result)
                //发送订阅消息
                _viewEvents.send(LoginViewEvent.Success)
            }.catch {
                //错误
//                _viewEvents.send(LoginViewEvent.ErrorMsg(it.message ?: ""))
                _viewEvents.send(LoginViewEvent.Success)//测试
            }.collect()
        }
    }
}

//数据自动更新ui
data class LoginViewState(
    val account: String = "",
    val password: String = "",
    val isLogged: Boolean = false,
    val isAgreement: Boolean = false,
    val cleanAccountSize: Dp = 0.dp,
    val cleanPasswordSize: Dp = 0.dp,
    val passwordRes: Int = R.mipmap.icon_eye_active,
    val visualTransformation: VisualTransformation = PasswordVisualTransformation(),
)

//订阅的消息类型
sealed class LoginViewEvent {
    object Success : LoginViewEvent()
    data class ErrorMsg(val msg: String) : LoginViewEvent()
}

sealed class LoginViewAction {
    object CleanAccount : LoginViewAction()
    object CleanPassword : LoginViewAction()
    object Login : LoginViewAction()
    object PasswordState : LoginViewAction()
    object UpdateAgreement : LoginViewAction()
    data class UpdateAccount(val account: String) : LoginViewAction()
    data class UpdatePassword(val password: String) : LoginViewAction()

}
